<template>
  <view class="x-carousel">
    <view class="_content">
      <view class="_ul">
        <view v-for="(item, index) in renderList" :key="index" :class="['_li', {active: index === currentIndex}]" :style="[liStyle]">
          <view class="_item">
            <view v-if="item.avatar" class="_avatar">
              <x-image :src="item.avatar" />
            </view>
            <view class="_dl">
              <view class="_dt">{{ item.name }}</view>
              <view class="_dd">
                购买了该商品，{{ item.time }}分钟前
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import XImage from '@/components/x-image';

export default {
  name: 'XCarouselFixed',
  components: {
    XImage
  },
  props: {
    list: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      renderList: null,
      transition: null,
      currentIndex: 0,
      height: 60,
      timeout: null
    };
  },
  computed: {
    liStyle() {
      return {
        transition: this.transition,
        transform: `translateY(-${this.currentIndex * 100}%)`
      };
    }
  },
  mounted() {
    if (this.list?.length < 3) {
      this.renderList = this.list;
      return;
    }
    const list = this.list.slice(0, 20);
    this.renderList = [...list, ...this.list.slice(0, 3)];
    this.start();
  },
  destroyed() {
    if (this.timeout) {
      clearTimeout(this.timeout);
    }
  },
  methods: {
    start() {
      this.timeout = setTimeout(() => {
        if (this.currentIndex === this.renderList.length - 3) {
          this.transition = '';
          this.currentIndex = 0;
        } else {
          this.transition = 'all 1s linear';
          this.currentIndex++;
        }
        this.start();
      }, this.currentIndex === 0 ? 0 : 1000);
    }
  }
};
</script>

<style lang="scss">
.x-carousel{
  position: relative; z-index: 10;
  ._content{
    overflow: hidden; position: relative;height: 250px;
    ._ul{ position: relative; height: 100%;padding-top: 90px}
    ._li{
      padding-bottom: 20px;
      opacity: 0;
      &.active{
        opacity: 1;
        + ._li{
          opacity: 1;
        }
      }
    }
    ._item{ display: flex; align-items: center; background: rgba(0, 0, 0, 1); border-radius: 50px; padding: 5px; }
    ._avatar{ width: 40px; height: 40px; border-radius: 50%; overflow: hidden; margin-right: 10px; background-color: #FFFFFF;}
    ._dl{ flex: 1;  display: flex; align-items: center;}
    ._dt{ font-size: 26px;  color: #FFBB32; }
    ._dd{ font-size: 26px; color: #ffffff; padding-right: 10px;}
  }
}
</style>
